package com.xiangban.yanglaodajie_platform.service;

import com.alibaba.fastjson.JSON;
import com.xiangban.yanglaodajie_platform.dao.ThirdApiConfigMapper;
import com.xiangban.yanglaodajie_platform.entity.ThirdApiConfig;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import com.xiangban.yanglaodajie_platform.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.xiangban.yanglaodajie_platform.utils.RedisUtil.fex;
import static com.xiangban.yanglaodajie_platform.utils.RedisUtil.tokenTime;

@Transactional
@Service
public class ThirdApiConfigService {
    @Autowired
    private ThirdApiConfigMapper thirdApiConfigMapper;

    @Autowired
    private RedisUtil redisUtil;

    public Map<String,String> getInfo (ThirdApiConfig thirdApiConfig){
        if (CommonUtils.BizEmpty(thirdApiConfig.getAccessId())){
            throw new BizException(ApiResultCode.FLAG_NO_ACCESS_ID);

        }
        if (CommonUtils.BizEmpty(thirdApiConfig.getAccessSecret())){
            throw new BizException(ApiResultCode.FLAG_NO_ACCESS_SECRET);
        }
        ThirdApiConfig info = thirdApiConfigMapper.getInfo(thirdApiConfig);
        if (info==null || !info.getAccessSecret().equals(thirdApiConfig.getAccessSecret())){
            throw new BizException(ApiResultCode.FLAG_FAIL_VOUCHER);
        }
        HashMap<String, String> res = new HashMap<>();
        res.put("token",generateToken(thirdApiConfig));

        return res;

    }

    public String generateToken(ThirdApiConfig thirdApiConfig) {
        String newToken = UUID.randomUUID().toString().replace("-", "");
        HashMap<String, Object> loginInfo = new HashMap<>();
        loginInfo.put("time", new Date().getTime());
        loginInfo.put("userId", thirdApiConfig.getAccessId());
        //获取上次token
        String oldToken = redisUtil.get(fex + thirdApiConfig.getAccessId());
        //清除上次登录token
        redisUtil.del(fex+oldToken,fex+thirdApiConfig.getAccessId());
        redisUtil.set(fex + thirdApiConfig.getAccessId(), newToken, tokenTime);
        redisUtil.set(fex +newToken, JSON.toJSONString(loginInfo), tokenTime);
        return newToken;
    }


}
